using System;
using System.Collections.Immutable;
using System.Linq;
using game_config;
using game_stuff;

namespace rogue_game
{
    [Serializable]
    public class RogueGamePlayer
    {
        public RogueGamePlayer(CharacterBody player)
        {
            Player = player;
            FinalBill = new FinalDeal();
            IsDead = false;
        }
        public RogueGamePlayer(CharacterBody player ,FinalDeal finalBill)
        {
            Player = player;
            FinalBill = finalBill;
            IsDead = false;
        }
        public bool IsDead { get; set; }

        public CharacterBody Player { get; }


        public FinalDeal FinalBill { get; }


        public void AddItem(ImmutableList<GameItem> gameItems)
        {
            Player.CharacterStatus.PickGameItems(gameItems);
            FinalBill.AddGain(gameItems);
        }

        public void AddItem(GameItem gameItems)
        {
            Player.CharacterStatus.PickGameItem(gameItems);
            FinalBill.AddGain(gameItems);
        }

        public PlayerStatusSave PlayerSave()
        {
            var playerCharacterStatus = Player.CharacterStatus;
            var playerStatusSave = PlayerStatusSave.GenSave(playerCharacterStatus, Player.Team, Player.BodySize,FinalBill);
            return playerStatusSave;
        }

        public void CheckDead()
        {
            IsDead = Player.CharacterStatus.SurvivalStatus.IsDead();
        }


        public void GenInGameCostBills()
        {
            var genCharTickMsg = Player.GenCharTickMsg();

            var itemChanges = genCharTickMsg.CharEvents.OfType<ItemChange>().Where(x => x.Cost);
            foreach (var itemChange in itemChanges)
            {
                FinalBill.AddCost(itemChange.Items);
            }
        }

        public void EnsureWalletItemInBag(GameItem[] nowInWallet)
        {
            var gameItems = nowInWallet.Where(x => IsPlayingItemAndEndNotClear(x.ItemId));
            var checkOutItems = FinalBill.CheckItems(gameItems);
            Player.CharacterStatus.EnsureWalletItemNum(checkOutItems);
        }

        private bool IsPlayingItemAndEndNotClear(item_id argItemId)
        {
            var configsItem = CommonConfig.Configs.items[argItemId];
            return configsItem.IsPlayingItem && !configsItem.IsEndClear;
        }

        public GameItem[] CountItems()
        {
            return FinalBill.CheckItems();
        }
    }
}